﻿using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System.Web;
using System;
using AspNet.Identity.Manager.Models;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using AspNet.Identity.Manager.Migrations;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;

namespace AspNet.Identity.Manager.Models
{
    // Sie können Benutzerdaten für den Benutzer durch Hinzufügen weiterer Eigenschaften zur User-Klasse hinzufügen. 
    // Weitere Informationen finden Sie unter "http://go.microsoft.com/fwlink/?LinkID=317594".
    public class ApplicationUser : IdentityUser 
    {
        public ApplicationUser() : base() { }
        public ApplicationUser(string userName) : base(userName) { }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false) 
        {
            Database.SetInitializer(new DbContextCustomInitializer());
        }
    }

    public class UserManager : UserManager<ApplicationUser>
    {
        public UserManager() : base(new UserStore<ApplicationUser>(new ApplicationDbContext())) { }
    }

    public class ApplicationRole: IdentityRole { }

    public class RoleManager : RoleManager<ApplicationRole>
    {
        public RoleManager() : base(new RoleStore<ApplicationRole>(new ApplicationDbContext())) { }
    }

    public class DbContextCustomInitializer : IDatabaseInitializer<ApplicationDbContext>
    {
        public void InitializeDatabase(ApplicationDbContext context)
        {
            //Configuration cfg = new Configuration();
            //cfg.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient");
            //DbMigrator dbMigrator = new DbMigrator(cfg);
            //dbMigrator.Update(); 
            
            //if (context.Database.Exists() && context.Database.CompatibleWithModel(true))
            //{
            //    return;
            //}
            //else
            //{
            //    context.Database.Delete();
            //    context.Database.Create();
            //    context.Database.ExecuteSqlCommand(sql);
            //}
        }
    }

}

namespace AspNet.Identity.Manager
{
    public static class IdentityHelper
    {
        // Wird für XSRF beim Verknüpfen externer Anmeldungen verwendet.
        public const string XsrfKey = "XsrfId";

        public static void SignIn(UserManager manager, ApplicationUser user, bool isPersistent)
        {
            IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
            authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }

        public const string ProviderNameKey = "providerName";
        public static string GetProviderNameFromRequest(HttpRequest request)
        {
            return request[ProviderNameKey];
        }

        public static string GetExternalLoginRedirectUrl(string accountProvider)
        {
            return "/Account/RegisterExternalLogin?" + ProviderNameKey + "=" + accountProvider;
        }

        private static bool IsLocalUrl(string url)
        {
            return !string.IsNullOrEmpty(url) && ((url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'))) || (url.Length > 1 && url[0] == '~' && url[1] == '/'));
        }

        public static void RedirectToReturnUrl(string returnUrl, HttpResponse response)
        {
            if (!String.IsNullOrEmpty(returnUrl) && IsLocalUrl(returnUrl))
            {
                response.Redirect(returnUrl);
            }
            else
            {
                response.Redirect("~/");
            }
        }
    }
}